<template>
  <div class="sjplatformtree">
    <el-input v-model="filterText" placeholder="检索关键字..." />
    <el-tree ref="treeRef" class="filter-tree" :data="data" :props="defaultProps" default-expand-all
      :filter-node-method="filterNode" :expand-on-click-node="false" @node-click="handleNodeClick">
      <template #default="{ node }">
        <el-tooltip v-if="isOverflowed(node)" class="item" effect="light" :content="node.label" placement="top">
          <span class="tree-node-content" :data-id="node.id">{{
            node.label
            }}</span>
        </el-tooltip>
        <span v-else class="tree-node-content" :data-id="node.id">{{
          node.label
          }}</span>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, onUnmounted } from "vue";
import { ElTree } from "element-plus";
import { useOrgTree } from "../../../hooks/SystemManager/Org/useOrgTree";
import emitter from "../../../utils/emitter";

let receivedProps = defineProps(["searchAll"]);

interface Tree {
  id: string;
  label: string;
  children?: Tree[];
}

const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  children: "children",
  label: "label",
};

watch(filterText, (val) => {
  if (treeRef.value) {
    // 确保 treeRef 已经初始化
    treeRef.value.filter(val);
  }
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 使用数据处理 Hook
const { data, orgStore, fetchData } = useOrgTree();
if (receivedProps.searchAll) {
  orgStore.searchAll = receivedProps.searchAll;
}
fetchData(); // 调用数据获取方法

const handleNodeClick = (node) => {
  orgStore.setSelectedOrgNode(node);
};

function isOverflowed(node) {
  //  await nextTick();
  //   const element = document.querySelector(`.tree-node-content[data-id="${node.id}"]`) as HTMLElement;
  //   if (element) {
  //     console.log(element);
  //     console.log("element.offsetWidth:", element.offsetWidth, "element.scrollWidth:", element.scrollWidth);
  //     return element.offsetWidth < element.scrollWidth;
  //   }
  //   return false;
  return node.label.length > 13;
}

//供外部调用刷新菜单树
emitter.on("refresh-org-tree", () => {
  fetchData();
});

onUnmounted(() => {
  //组件卸载后解绑
  emitter.off("refresh-org-tree");
});
</script>